package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.CarlaClassicVo;
import com.jdy.haoduoai.model.CartoonVo;
import com.jdy.haoduoai.model.DeviceVersionInfo;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.SocketMachineInfo;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.service.CountDownService;
import com.jdy.haoduoai.socket.DeviceStateListener;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.BlurTransformation;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.LeXiaoXiaoBanLog;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.ServiceUtils;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.BatteryIndicator;
import com.jdy.haoduoai.view.HSeekBar;
import com.jdy.haoduoai.view.MusicPlayView;
import com.jdy.haoduoai.view.StorageIndicator;
import com.jdy.haoduoai.view.scrollview.ObservableScrollView;
import com.jdy.haoduoai.view.scrollview.OnScrollChangedCallback;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

//import com.jdy.haoduoai.R;

/**
 * 
 * @author hf
 * 
 */
@SuppressLint("HandlerLeak")
public class DevicePropertyActivity extends BaseActivity implements
    OnSeekBarChangeListener, View.OnClickListener,
        OnScrollChangedCallback, OnDataReceivedListener, DeviceStateListener {

  private static final String TAG = DevicePropertyActivity.class
      .getSimpleName();

  @InjectView(id = R.id.countDownView)
  private HSeekBar mCountDownView;
  @InjectView(id = R.id.shutdownRelativeLayout, click = true)
  private View shutdownRelativeLayout;
  @InjectView(id = R.id.storageTextView)
  private TextView storageTextView;
  @InjectView(id = R.id.currentVersionTextView)
  private TextView mVersionTextView;
  @InjectView(id = R.id.macIdTextView)
  private TextView mMacIdTextView;
  @InjectView(id = R.id.tv_title)
  private TextView tv_title;
  @InjectView(id = R.id.powerTextView)
  private TextView mPowerTextView;
  @InjectView(id = R.id.projector_onoff)
  private CheckBox mProjectorCheckBox;
  @InjectView(id = R.id.activatioinStateRelativeLayout, click = true)
  private View activatioinStateRelativeLayout;
  @InjectView(id = R.id.shutdownTxt)
  private TextView mShutDownTxt;
  @InjectView(id = R.id.activationStateTextView)
  private TextView mActivationStateTextView;
  @InjectView(id = R.id.validUntilToTextView)
  private TextView mValidUntilToTextView;
  @InjectView(id = R.id.upgradeDeviceRelativeLayout)
  private RelativeLayout mUpgradeDeviceRelativeLayout;
  @InjectView(id = R.id.connect2WifiLayout, click = true)
  private RelativeLayout mConnectWifiLayout;
  @InjectView(id = R.id.breath_light_layout, click = true)
  private RelativeLayout mBreathLightLayout;
  @InjectView(id = R.id.recoveryRelativeLayout)
  private RelativeLayout mRecoveryRelativeLayout;
  @InjectView(id = R.id.bindOtherDeviceRelativeLayout)
  private RelativeLayout mBindOtherDeviceRelativeLayout;
  @InjectView(id = R.id.volume_seek, click = true)
  private SeekBar volume_seek;
  @InjectView(id = R.id.vol_down, click = true)
  private View vol_down;
  @InjectView(id = R.id.vol_up, click = true)
  private View vol_up;
  @InjectView(id = R.id.back, click = true)
  private View back;
  @InjectView(id = R.id.playmode, click = true)
  private ImageView imgPlayMode;
//  @InjectView(id = R.id.switch_indicator_relativelayout)
//  private RelativeLayout mSwitchRelativeLayout;
  @InjectView(id = R.id.switch_notification_textview)
  private TextView mSwitchNotificationTextView;
  @InjectView(id = R.id.head)
  private RelativeLayout head;
  @InjectView(id = R.id.img_headbg)
  private ImageView img_headbg;
  @InjectView(id = R.id.playbackryl)
  private RelativeLayout playbackryl;
  @InjectView(id = R.id.layout_media_play_view)
  private MusicPlayView mPlayView;
  @InjectView(id = R.id.play, click = true)
  private ImageButton play;
  @InjectView(id = R.id.prebtn, click = true)
  private ImageButton prebtn;
  @InjectView(id = R.id.nextbtn, click = true)
  private ImageButton nextbtn;
//  @InjectView(id = R.id.forward, click = true)
//  private ImageButton forward;
//  @InjectView(id = R.id.rewindbtn, click = true)
//  private ImageButton rewindbtn;
  @InjectView(id = R.id.scrollview)
  private ObservableScrollView mScrollView;

  private Animation mBottomUpAnimation;
  private TranslateAnimation mSlideUpAnimation;
  private TextView wifiStateTv;

  private LeUser mLeUser;
  private LeMachine mLeBaby;
//  @SuppressWarnings("unused")
//  private long mRemainningSeconds = 0;
  private BroadcastReceiver mReceiver = null;

  @InjectView(id = R.id.storage_indicator)
  private StorageIndicator mStorageIndicator;
  @InjectView(id = R.id.battery_indicator)
  private BatteryIndicator mBatteryIndicator;

  private int VideoId, lastVideoId;

//  @SuppressWarnings("unused")
//  private final boolean mIsDeviceOnline = false;
  private PlayState mPlayState = PlayState.None;
//  @SuppressWarnings("unused")
//  private MediaType mMediaType = MediaType.None;
  private ImageView imageCover;
  private int mCurrentPlayMode = 2;
  private int[] playMode;
  private int lastParentid, Parentid;

  private final long TIME_GAP = 3 * 1000;

  private long last_timestamp;
  private long current_timestamp;

  private String strTitle;

  private int mTimeCount = 0;
  private int lastPlayMode = 3;



//  Runnable runnable = new Runnable(){
//    @Override
//    public void run() {
//     // if (mImHelper != null && mImHelper.isLogin()) {
//        try {
//          JSONObject dataJson = new JSONObject();
//          dataJson.put("code", 202);
//          dataJson.put("act", "machineinfo");
//          SocketThreadManager.getInstance().send(dataJson.toString());
//
////          stopCountdownTimer();
////          startCountdownTimer();
//        } catch (JSONException e) {
//          e.printStackTrace();
//        } catch (Exception e) {
//          e.printStackTrace();
//        }
//    //  }
//
//      mHandler.postDelayed(this, 25000);
//    }
//  };

  private CountDownTimer mCountDownTimer;

  private void startCountdownTimer() {
    mCountDownTimer = new CountDownTimer(25 * 1000, 1000) {

      public void onTick(long millisUntilFinished) {

        //here you can have your logic to set text to edittext
      }

      public void onFinish() {
        LeConfig.isDeviceConnect = false;

                 if (mPlayView != null && mPlayView.isPlay()) {
                    mPlayView.pause();
                  }
                  wifiStateTv.setText("设备未连接");
                  mPowerTextView.setText("--%");
                  storageTextView.setText("N/A");
                  strTitle = "设备未连接";
                  tv_title.setText("设备未连接");

                  lastParentid = 0;
                  lastVideoId = 0;

                  imageCover
                      .setImageResource(R.drawable.device_property_defaultcover);
                  playbackryl
                      .setBackgroundResource(R.drawable.device_property_defaultcoverbig);
      }

    }.start();
  }

  private void stopCountdownTimer() {
    if (mCountDownTimer != null) {
      mCountDownTimer.cancel();
      mCountDownTimer = null;
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.device_property_layout);

    hideTitleView();

//    mImHelper = LeXiaoXiaoBanApp.getInstance().getImHelper();
  //  if (mImHelper != null && mImHelper.isLogin()) {
      SocketThreadManager.getInstance().setDataReceivedListener(this);
    SocketThreadManager.getInstance().setDeviceStateListener(this);
     // mImHelper.setIMParseListener(this);

      try {
        JSONObject dataJson = new JSONObject();
        dataJson.put("code", 202);
        dataJson.put("act", "machineinfo");
        SocketThreadManager.getInstance().send(dataJson.toString());

//        stopCountdownTimer();
//        startCountdownTimer();
      } catch (JSONException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

    //  mHandler.postDelayed(runnable, 15000);
//    }

    wifiStateTv = (TextView) findViewById(R.id.wifiStateTv);

    if (LeConfig.isDeviceConnect) {
      wifiStateTv.setText("设备已连接");
      tv_title.setText("当前暂无播放");
      strTitle = "当前暂无播放";
    } else {
      wifiStateTv.setText("设备未连接");
      tv_title.setText("设备未连接");
      strTitle = "设备未连接";
      // if (LeConfig.isDeviceOnline == 0) {
      // wifiStateTv.setText("设备已连接");
      // } else {
      // wifiStateTv.setText("设备未连接");
      // }
    }

    mScrollView.setOnScrollChangedCallback(this);
    playMode = new int[] { R.drawable.single_song_mode,
        R.drawable.single_song_repeat_mode, R.drawable.sequence_song_mode };

    mBottomUpAnimation = AnimationUtils.loadAnimation(this, R.anim.bottom_up);
    mBottomUpAnimation.setAnimationListener(new AnimationListener() {
      @Override
      public void onAnimationStart(Animation animation) {
        // TODO
      }

      @Override
      public void onAnimationRepeat(Animation animation) {
        // TODO

      }

      @Override
      public void onAnimationEnd(Animation animation) {
        // TODO
      }
    });

    LeConfig.PlayMode = LePreference.getInstance().getInt("playmode", 3);
    mCurrentPlayMode = LeConfig.PlayMode - 1;
    if (mCurrentPlayMode < 0) {
      mCurrentPlayMode = 0;
    }

    lastPlayMode = LeConfig.PlayMode;
    strTitle = tv_title.getText().toString().trim();
    //imgPlayMode.setBackgroundResource(playMode[mCurrentPlayMode]);

    LeConfig.isInternetAvailable = Tools.isNetworkAvailable(this);
    volume_seek.setMax(100);
    volume_seek.setOnSeekBarChangeListener(this);

    int volume = LePreference.getInstance().getInt("devicevolume", 80);
    volume_seek.setProgress(volume);

    shutdownRelativeLayout.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
            DevicePropertyActivity.this).setMessage("确定要关闭小小班设备？")
            .setNegativeButton("取消", new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("确定", new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                if (!LeConfig.isDeviceConnect) {
                  dialog.dismiss();
                  CommonUtil.showToask(DevicePropertyActivity.this, "设备不在线");
                } else {
                  turnPowerOff();
                  dialog.dismiss();
                }
              }
            });
        if (!isFinishing()) {
          cdb.create().show();
        }

      }
    });

    Picasso.with(DevicePropertyActivity.this)
        .load(R.drawable.device_property_defaultcoverbig)
        .transform(new BlurTransformation(20)).into(new Target() {
          @SuppressWarnings("deprecation")
          @Override
          public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            playbackryl.setBackgroundDrawable(new BitmapDrawable(bitmap));
          }

          @Override
          public void onBitmapFailed(Drawable errorDrawable) {
            // TODO
          }

          @Override
          public void onPrepareLoad(Drawable placeHolderDrawable) {
            // TODO
          }
        });

    handleCountDownLogic();

    getMachineDetails();

//    TIMManager.getInstance().setConnectionListener(new TIMConnListener() {
//
//      @Override
//      public void onWifiNeedAuth(String arg0) {
//        // TODO Auto-generated method stub
//
//      }
//
//      @Override
//      public void onDisconnected(int arg0, String arg1) {
//        LeConfig.isDeviceConnect = false;
//
//        if (mPlayView.isPlay()) {
//          mPlayView.pause();
//        }
//        wifiStateTv.setText("设备未连接");
//        tv_title.setText("设备未连接");
//        strTitle = "设备未连接";
//
//        mPowerTextView.setText("--%");
//        storageTextView.setText("N/A");
//
//        lastParentid = 0;
//        lastVideoId = 0;
//
//        imageCover.setImageResource(R.drawable.device_property_defaultcover);
//        playbackryl
//            .setBackgroundResource(R.drawable.device_property_defaultcoverbig);
//      }
//
//      @Override
//      public void onConnected() {
//        if (mImHelper != null && mImHelper.isLogin()) {
//          try {
//            JSONObject dataJson = new JSONObject();
//            dataJson.put("code", "app");
//            dataJson.put("act", "machineinfo");
//            mImHelper.send(dataJson.toString());
//
//            stopCountdownTimer();
//            startCountdownTimer();
//          } catch (JSONException e) {
//            e.printStackTrace();
//          } catch (Exception e) {
//            e.printStackTrace();
//          }
//        }
//
//      }
//    });

  }

  private void handleCountDownLogic() {
    long custom_close_at = LePreference.getInstance().getLong(
        "custom_close_at", 0); // 上次定时关机时刻
    long custom_interval = LePreference.getInstance().getLong(
        "custom_close_interval", 0); // 上次定时关机时间间隔

    if ((System.currentTimeMillis() - custom_close_at) >= custom_interval) {
      mTimeCount = 0;
      saveVariable();
      mCountDownView.setProgress(mTimeCount);
      LePreference.getInstance().delete("custom_close_at");
      LePreference.getInstance().delete("custom_close_interval");
    }

    mCountDownView.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {
        if (!LeConfig.isDeviceConnect) {
          CommonUtil.showToask(DevicePropertyActivity.this, "设备不在线");
          mCountDownView.setProgress(mTimeCount);
        } else {
          current_timestamp = System.currentTimeMillis();
          if (current_timestamp - last_timestamp > TIME_GAP) {
            last_timestamp = current_timestamp;
            requestDeviceShutdown(seekBar.getProgress() * 60 * 1000);
          } else {
            mCountDownView.setProgress(mTimeCount);
          }
        }
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

      }

      @Override
      public void onProgressChanged(SeekBar seekBar, int progress,
          boolean fromUser) {

      }
    });
  }

  private void saveVariable() {
    SharedPreferences prefs = getSharedPreferences("TimeLeft",
        Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("timeleft", mTimeCount);
    editor.commit(); // important, otherwise it wouldn't save.
  }

  private void getVariable() {
    SharedPreferences prefs = getSharedPreferences("TimeLeft", 0);
    mTimeCount = prefs.getInt("timeleft", 0);
  }

  @SuppressWarnings("deprecation")
  private void parseJson(String jsonData) {
    if (Tools.isNotEmpty(jsonData)) {
      mLeBaby = JsonSerializer.getInstance().deserialize(jsonData,
          LeMachine.class);
    }

    mMacIdTextView.setText(mLeUser.machine.id);

    if (mLeBaby != null) {
      if (Tools.isNotEmpty(mLeBaby.version)) {
        mVersionTextView.setText("当前版本: " + mLeBaby.version);
      } else {
        mVersionTextView.setText("N/A");
      }

      if (LeConfig.isDeviceConnect) {
        mPowerTextView.setText(String.valueOf(mLeBaby.power) + "%");
        mBatteryIndicator.updateBattery(mLeBaby.power / 100.0f);
      }

      volume_seek.setProgress(mLeBaby.volume);
      LePreference.getInstance().save("devicevolume", mLeBaby.volume);
    } else {
      // mPowerTextView.setText("--%");

      mLeBaby = mLeUser.machine;

      toastShow("设备不在线");
      LeConfig.isDeviceConnect = false;
      wifiStateTv.setText("设备未连接");
      mPowerTextView.setText("--%");
      storageTextView.setText("N/A");
      tv_title.setText("设备未连接");
      strTitle = "设备未连接";

      lastParentid = 0;
      lastVideoId = 0;

      imageCover.setImageResource(R.drawable.device_property_defaultcover);
      playbackryl
          .setBackgroundResource(R.drawable.device_property_defaultcoverbig);

      volume_seek.setProgress(mLeUser.machine.volume);

      LePreference.getInstance().save("devicevolume", mLeUser.machine.volume);
    }

    mActivationStateTextView.setTextColor(getResources().getColor(
        R.color.activated_font_color));
    mActivationStateTextView.setText("已激活");

    mValidUntilToTextView = (TextView) findViewById(R.id.validUntilToTextView);

    if (mLeBaby != null && Tools.isNotNullStr(mLeBaby.activate)) {
      mValidUntilToTextView.setText("有效期至" + mLeBaby.activate.expired_at);
    }

    if (mLeBaby != null && LeConfig.isDeviceConnect) {
      long usedSize = Long.valueOf(mLeBaby.usesize);
      long totalSize = Long.valueOf(mLeBaby.discsize);

      if (totalSize != 0) {
        mStorageIndicator.convert2Angle(totalSize - usedSize, totalSize);
      }

      storageTextView.setText(android.text.format.Formatter.formatFileSize(
          this, (totalSize - usedSize) * 1024).trim()
          + "/"
          + android.text.format.Formatter.formatFileSize(this,
              totalSize * 1024).trim());
    }
  }

  private void getMachineStatus() {

    try {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("code", 202);
      jsonObject.put("act", "videostatu");
      SocketThreadManager.getInstance().send(jsonObject.toString());
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

//    new CustomAsyncTask(this, new IAsyncTask() {
//      @Override
//      public void onRecieveData(Activity activity, ResponseResult result) {
//        if (result.isSuccess()) {
//       //   parseJson(result.data);
//        }
//      }
//
//      @Override
//      public ResponseResult doInbackground(Activity activity) {
//        if (mLeUser == null) {
//          mLeUser = Tools.restoreLeUser();
//        }
//
//        String sno = mLeUser.sno;
//        String macId = mLeUser.machine.id;
//
//        HashMap<String, Object> param_ = new HashMap<String, Object>();
//        param_.put(HttpUtils.TAG_SNO_I, sno);
//        param_.put("act", "videostatu");
//        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
//
//        return HttpUtils.startRequest(HttpUtils.API_URL
//                        + "/api/1.0/device/remote", param_,
//                HttpUtils.TAG_GET_REQUEST);
//      }
//    }).execute();
  }

  private void getMachineDetails() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          parseJson(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        String sno = mLeUser.sno;
     //   String macId = mLeUser.machine.id;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.BIND_DEVICE_METHOD_POST, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void versionAlert(String message) {
    String strBabyVer = "";

    if (mLeBaby == null) {
        mLeBaby = LeXiaoXiaoBanApp.getInstance().getBaby();
        if (mLeBaby == null && mLeUser != null) {
            mLeBaby = mLeUser.machine;
        }
    }

    if (mLeBaby != null) {
      strBabyVer = mLeBaby.version;
    }

    CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
        DevicePropertyActivity.this).setTitle("您当前的版本号:" + strBabyVer)
        .setMessage(message).setNegativeButton("取消", new OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        }).setPositiveButton("确定", new OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
    if (!isFinishing()) {
      cdb.create().show();
    }
  }

  @SuppressWarnings("deprecation")
  private void initView() {
    imageCover = (ImageView) mPlayView.findViewById(R.id.avatar);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    if (LeConfig.isDeviceActivated) {
      mActivationStateTextView.setTextColor(getResources().getColor(
          R.color.activated_font_color));
      mActivationStateTextView.setText("已激活");
      activatioinStateRelativeLayout.setClickable(false);
    } else {
      mActivationStateTextView.setTextColor(getResources()
          .getColor(R.color.red));
      mActivationStateTextView.setText("未激活");
      activatioinStateRelativeLayout.setClickable(true);
    }

    if (ServiceUtils.isMyServiceRunning(this, CountDownService.class)) {
      mCountDownView.invalidate();
    }

    int style = com.jdy.haoduoai.view.ProgressHintDelegate.POPUP_FOLLOW;
    mCountDownView.getHintDelegate().setPopupStyle(style);
    getVariable();
    mCountDownView.setProgress(mTimeCount);

    mProjectorCheckBox
        .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView,
              boolean isChecked) {
            final boolean lightChecked = isChecked;
            new CustomAsyncTask(DevicePropertyActivity.this, new IAsyncTask() {

              @Override
              public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                  mProjectorCheckBox.setChecked(lightChecked);
                  if (lightChecked) {
                    Vibrator v = (Vibrator) DevicePropertyActivity.this
                        .getSystemService(Context.VIBRATOR_SERVICE);
                    v.vibrate(500);
                  }
                } else {
                  if (Tools.isNotEmpty(result)) {
                    toastShow(result.data);
                  }
                }
              }

              @Override
              public ResponseResult doInbackground(Activity activity) {
                String op;
                if (lightChecked) {
                  op = "on";// for open
                } else {
                  op = "off";// for close
                }

                if (mLeUser == null) {
                  mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();

                int videoId = -1, volume = -1, minutes = -1;
                param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_ACTION_I, "light");
                param_.put(HttpUtils.TAG_OPERATION_I, op);
               // param_.put("mode", "im");

                if (videoId != -1)
                  param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(videoId));
                if (volume != -1)
                  param_.put(HttpUtils.TAG_VOLUMN_I, String.valueOf(volume));
                if (minutes != -1)
                  param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));

                return HttpUtils.startRequest(HttpUtils.API_URL
                    + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
                    HttpUtils.TAG_GET_REQUEST);

              }
            }).execute();
          }
        });

    mUpgradeDeviceRelativeLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        new CustomAsyncTask(DevicePropertyActivity.this, new IAsyncTask() {

          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {
            if (result.isSuccess()) {

              DeviceVersionInfo di = JsonSerializer.getInstance().deserialize(
                      result.data, DeviceVersionInfo.class);

              if (Tools.isNotEmpty(di)) {
                if (mLeBaby == null) {
                  versionAlert("最新设备版本号:Haoduoai-V" + di.value);
                } else {
                  if (Tools.isEmpty(mLeBaby.version)) {
                    versionAlert("最新设备版本号:Haoduoai-V" + di.value);
                  } else {
                    int newestVersion = Tools.strToInt(result.data.replaceAll(
                            "[\\s.]", ""));

                    int currentVersion = Tools.strToInt(mLeBaby.version.replaceAll(
                            "\\D+", ""));

                    String alertMessage = null;

                    if (newestVersion > currentVersion) {
                      alertMessage = "最新设备版本号:Haoduoai-V" + di.value
                              + ",请在设备上更新";
                    } else {
                      alertMessage = "您的版本已经是最新版本啦!";
                    }
                    versionAlert(alertMessage);
                    LeXiaoXiaoBanLog.e(TAG, "current version :" + currentVersion
                            + "newest version :" + newestVersion);
                  }
                }
              }
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {

            if (mLeUser == null) {
              mLeUser = Tools.restoreLeUser();
            }

            HashMap<String, Object> param_ = new HashMap<String, Object>();

            param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

            return HttpUtils.startRequest(HttpUtils.API_URL
                + HttpUtils.GET_NEWEST_DEVICE_VERSION_METHOD_GET, param_,
                HttpUtils.TAG_GET_REQUEST);
          }
        }).execute();
      }
    });

    mRecoveryRelativeLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
            DevicePropertyActivity.this).setTitle("提示")
            .setMessage("确定要将设备恢复出厂设置吗?")
            .setNegativeButton("取消", new OnClickListener() {

              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("确定", new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                if (!LeConfig.isDeviceConnect) {
                  dialog.dismiss();
                  CommonUtil.showToask(DevicePropertyActivity.this, "设备不在线");
                } else {
                  recoveryDeviceRequest();
                  dialog.dismiss();
                }
              }
            });

        if (!isFinishing()) {
          cdb.create().show();
        }
      }
    });

    mBindOtherDeviceRelativeLayout
        .setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
//            Intent t = new Intent(DevicePropertyActivity.this,
//                BindDeviceActivity.class);
//            t.putExtra("fromPage", "DevicePropertyActivity");
//            startActivity(t);
//            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
          }
        });

  }

  /**
   * Tell if device is online
   * 
   * @return
   */
  @SuppressWarnings("unused")
  private boolean isDeviceOnline() {
    if (LeConfig.isInternetAvailable) {
      if (mLeUser == null) {
        mLeUser = Tools.restoreLeUser();
      }

      int videoId = -1, uid = -1, volume = -1, minutes = -1;

      HashMap<String, Object> param_ = new HashMap<String, Object>();
      param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
      param_.put(HttpUtils.TAG_ACTION_I, "status");
      param_.put(HttpUtils.TAG_OPERATION_I, "control");
    //  param_.put("mode", "im");

      if (videoId != -1) {
        param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(videoId));
      }
      if (uid != -1) {
        param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
      }
      if (volume != -1) {
        param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
      }
      if (minutes != -1) {
        param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
      }
      param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

      ResponseResult r = HttpUtils.startRequest(HttpUtils.API_URL
          + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
          HttpUtils.TAG_GET_REQUEST);

      if (r != null) {
        if (r.data.equals("设备不在线")) {
          LeConfig.isDeviceConnect = false;
          return false;
        } else if (r.data.equals("成功")) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      toastShow("请检查网络连接");

      return false;
    }
  }

  private void turnPowerOff() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        toastShow("成功");
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        int videoId = -1, volume = -1, minutes = -1;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "power");
        param_.put(HttpUtils.TAG_OPERATION_I, "off");
       // param_.put("mode", "im");

        if (videoId != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(videoId));
        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();

  }

  /**
   * Set the state of the device to it's manufacture state.
   */
  private void recoveryDeviceRequest() {
    new CustomAsyncTask(DevicePropertyActivity.this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        toastShow(result.data);
      }

      @SuppressWarnings("deprecation")
      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        int videoId = -1, volume = -1, minutes = -1;
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "init");
        param_.put(HttpUtils.TAG_OPERATION_I, "control");
       // param_.put("mode", "im");

        if (videoId != -1)
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(videoId));
        if (volume != -1)
          param_.put(HttpUtils.TAG_VOLUMN_I, String.valueOf(volume));
        if (minutes != -1)
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.device_property_layout, menu);
    return true;
  }

  private void requestDeviceShutdown(final long totalMillis) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        toastShow(result.data);

        if (!result.isSuccess()) {
          mCountDownView.setProgress(mTimeCount);
        } else {
          mTimeCount = (int) (totalMillis / (60 * 1000));

          saveVariable();
          LePreference.getInstance().save("custom_close_at", current_timestamp);
          LePreference.getInstance().save("custom_close_interval", totalMillis);
        }
      }

      @SuppressWarnings("deprecation")
      @Override
      public ResponseResult doInbackground(Activity activity) {
        int closeTime = (int) (totalMillis / 60000);
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        int videoId = -1, volume = -1;
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "timingoff");
        param_.put(HttpUtils.TAG_OPERATION_I, "control");
       // param_.put("mode", "im");

        if (videoId != -1)
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(videoId));
        if (volume != -1)
          param_.put(HttpUtils.TAG_VOLUMN_I, String.valueOf(volume));
        if (closeTime != -1)
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(closeTime));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  @SuppressWarnings("unused")
  private void updateGUI(Intent intent) {
    if (intent.getExtras() != null) {
//      this.mRemainningSeconds = intent.getLongExtra(
//          CountDownService.REMAINNING_SECONDS, 0);
      float v = intent.getFloatExtra(CountDownService.VELOCITY, 0);
      float i = intent.getFloatExtra(CountDownService.INITIAL_POSITION, 0);
      long w = intent.getLongExtra(CountDownService.TOTAL_MILLIS, 0);
    }
  }

  @Override
  public void onResume() {
    super.onResume();

    MobclickAgent.onResume(this);

    mLeUser = ((LeXiaoXiaoBanApp) getApplication()).getUser();
    if (mLeUser != null && mLeUser.machine != null) {
      LeConfig.MAC_ID = mLeUser.machine.id;
      LeConfig.PHONE_NUM = mLeUser.id;

      volume_seek.setProgress(mLeUser.machine.volume);
    }

    mMacIdTextView.setText(LeConfig.MAC_ID);


    getMachineStatus();

    initView();

    mReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (CountDownService.COUNTDOWN_BR.equals(action)) {
          updateGUI(intent);
        } else if ("device.details.update.event".equals(action)) {
          SocketMachineInfo sminfo = (SocketMachineInfo) intent
              .getSerializableExtra("socketmachineinfo");
          if (sminfo != null) {
            mPowerTextView.setText(sminfo.power + "%");
            mBatteryIndicator.updateBattery(sminfo.power / 100.0f);
            mVersionTextView.setText("当前版本: " + sminfo.version);
            if (sminfo.usesize != 0 && sminfo.discsize != 0) {
              storageTextView.setText(android.text.format.Formatter
                  .formatFileSize(context,
                      (sminfo.discsize - sminfo.usesize) * 1024)
                  + "/"
                  + android.text.format.Formatter.formatFileSize(context,
                      sminfo.discsize * 1024));
            }
            if (sminfo.discsize != 0) {
              mStorageIndicator.convert2Angle(sminfo.discsize - sminfo.usesize,
                  sminfo.discsize);
            }
            if (sminfo.lightopen == 1) {
              mProjectorCheckBox.setChecked(true);
            } else {
              mProjectorCheckBox.setChecked(false);
            }

            if (sminfo.charge == 1) {
              mBatteryIndicator.setChargeState(true);
            } else {
              mBatteryIndicator.setChargeState(false);
            }
          }
        }
      }
    };

    IntentFilter filter = new IntentFilter();
    filter.addAction(CountDownService.COUNTDOWN_BR);
    filter.addAction("device.details.update.event");
    registerReceiver(mReceiver, filter);
    LeXiaoXiaoBanLog.i(TAG, "Registered broacast receiver");

    if (mPlayState == PlayState.None || mPlayState == PlayState.Stop) {
      play.setImageResource(R.drawable.pause_new_icon);
    }

    if (mPlayState == PlayState.Offline) {
      mTitleText.setText("设备已掉线");
    }

    if (mPlayState.equals(PlayState.Pause) || mPlayState.equals(PlayState.Stop)) {
      mPlayView.pause();
    } else if (mPlayState.equals(PlayState.Playing)) {
      mPlayView.play();
    }
    mPlayView.setVisibility(View.VISIBLE); // 解决偶尔不显示
  }

  @Override
  public void onPause() {
    super.onPause();
    MobclickAgent.onPause(this);

    if (mReceiver != null) {
      unregisterReceiver(mReceiver);
      mReceiver = null;
    }
    LeXiaoXiaoBanLog.i(TAG, "Unregistered broacast receiver");
    saveVariable();
  }

  @Override
  public void onStop() {
    try {
      if (mReceiver != null) {
        unregisterReceiver(mReceiver);
        mReceiver = null;
      }
    } catch (Exception e) {

    }
    super.onStop();
  }

  @Override
  public void onDestroy() {

    SocketThreadManager.getInstance().removeDataReceivedListener(this);
    SocketThreadManager.getInstance().removeDeviceStateListener(this);

    if (mHandler != null) {
      mHandler.removeCallbacksAndMessages(null);
    }

    stopCountdownTimer();

    super.onDestroy();
  }

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    // TODO
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {

  }

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {
    setvolume(seekBar.getProgress());
  }

  private void setvolume(final int volume) {
    CustomAsyncTask cat = new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          // TODO
        } else {
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        int videoId = -1, uid = -1, minutes = -1;
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "volume");
        param_.put(HttpUtils.TAG_OPERATION_I, "control");
      //  param_.put("mode", "im");

        if (videoId != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(videoId));
        }
        if (uid != -1) {
          param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    });
    cat.setSerialExecutor();
    cat.execute();
  }

  private void switchPlayMode() {
    String notificationTitle = "";
    mCurrentPlayMode++;
    mCurrentPlayMode = mCurrentPlayMode % 3;
  //  imgPlayMode.setBackgroundResource(playMode[mCurrentPlayMode]);

    /**
     * 单曲循环
     列表循环
     单曲播放
     */
    switch (mCurrentPlayMode) {
    case 0:
      notificationTitle = "单曲播放";
      break;
    case 1:
      notificationTitle = "单曲循环";
      break;
    case 2:
      notificationTitle = "列表循环";
      break;
    default:
      notificationTitle = "发生未知错误";
      break;
    }

    LeConfig.PlayMode = mCurrentPlayMode + 1;
    LePreference.getInstance().save("playmode", LeConfig.PlayMode);

  //  mSwitchNotificationTextView.setText(notificationTitle);
 //   mSwitchRelativeLayout.clearAnimation();
//    mSlideUpAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,
//        Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0, Animation.ABSOLUTE,
//        -mSwitchRelativeLayout.getHeight());
//
//    mSlideUpAnimation.setRepeatCount(1);
//    mSlideUpAnimation.setDuration(1500);
//    mSlideUpAnimation.setRepeatMode(Animation.REVERSE);
//    mSwitchRelativeLayout.startAnimation(mSlideUpAnimation);



    Toast toast = Toast.makeText(this, notificationTitle, Toast.LENGTH_LONG);
    toast.setGravity(Gravity.TOP, 0, playbackryl.getHeight()- Tools.getPixelByDip(this, 50));
    toast.show();
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.activatioinStateRelativeLayout:
      Intent intent = new Intent(DevicePropertyActivity.this,
          InputActivationActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
          | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);

      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
    case R.id.vol_down:
      setvolume(0);
      volume_seek.setProgress(0);
      LePreference.getInstance().save("devicevolume", 0);
      break;
    case R.id.vol_up:
      setvolume(100);
      volume_seek.setProgress(100);
      LePreference.getInstance().save("devicevolume", 100);
      break;
    case R.id.back:
      this.finish();
      break;
    case R.id.playmode:

      if (PlayState.Pause.equals(mPlayState) && LeConfig.isDeviceConnect) {
        switchPlayMode();
      } else if (PlayState.Playing.equals(mPlayState)
          && LeConfig.isDeviceConnect) {
        new AsyncTask<Void, Void, ResponseResult>() {
          @Override
          protected void onPostExecute(ResponseResult result) {
            if (Tools.isNotEmpty(result) && result.isSuccess()) {
              switchPlayMode();
            } else {
              if (Tools.isNotNullStr(result)) {
                toastShow(result.data);
              }
            }
          }

          @Override
          protected ResponseResult doInBackground(Void... params) {
            int targetMode = mCurrentPlayMode + 1;
            if (targetMode >= playMode.length) {
              targetMode = 0;
            }
            return HttpUtils.operateDevice(mLeUser.sno, HttpUtils.KEY, "play",
                "continue", VideoId, -1, -1, -1, targetMode + 1, "cartoon");
          }
        }.execute();
      }

      break;
    case R.id.play:
      if (mPlayState == PlayState.Playing && LeConfig.isDeviceConnect) {

       // if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 202);
            jsonObject.put("act", "ctlvideo");
            jsonObject.put("data", "pause");
            SocketThreadManager.getInstance().send(jsonObject.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
       // }

        play.setImageResource(R.drawable.play_new_icon);
        mPlayView.pause();
      } else if (mPlayState == PlayState.Pause && LeConfig.isDeviceConnect) {

       // if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 202);
            jsonObject.put("act", "ctlvideo");
            jsonObject.put("data", "resume");
            SocketThreadManager.getInstance().send(jsonObject.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
        //}

        if (lastPlayMode != LeConfig.PlayMode) {
//          new AsyncTask<Void, Void, ResponseResult>() {
//            @Override
//            protected void onPostExecute(ResponseResult result) {
//              if (result.isSuccess()) {
//                lastPlayMode = LeConfig.PlayMode;
//              }
//            }
//
//            @Override
//            protected ResponseResult doInBackground(Void... params) {
//              return HttpUtils.operateDevice(mLeUser.sno, HttpUtils.KEY,
//                  "play", "continue", VideoId, -1, -1, -1, LeConfig.PlayMode,
//                  "cartoon");
//            }
//          }.execute();

        } else {
          // TODO
        }

        play.setImageResource(R.drawable.pause_new_icon);
        mPlayView.play();
      }
      break;
    case R.id.prebtn:
      if ( LeConfig.isDeviceConnect) {
        try {
          JSONObject jsonObject = new JSONObject();
          jsonObject.put("code", 202);
          jsonObject.put("act", "ctlvideo");
          jsonObject.put("data", "previous");
          SocketThreadManager.getInstance().send(jsonObject.toString());
        } catch (JSONException e) {
          e.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      break;
    case R.id.nextbtn:
      if (LeConfig.isDeviceConnect) {
        try {
          JSONObject jsonObject = new JSONObject();
          jsonObject.put("code", 202);
          jsonObject.put("act", "ctlvideo");
          jsonObject.put("data", "next");
          SocketThreadManager.getInstance().send(jsonObject.toString());
        } catch (JSONException e) {
          e.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      break;
//    case R.id.forward:
//      if ( LeConfig.isDeviceConnect) {
//        try {
//          JSONObject jsonObject = new JSONObject();
//          jsonObject.put("code", 202);
//          jsonObject.put("act", "ctlvideo");
//          jsonObject.put("data", "speed");
//          SocketThreadManager.getInstance().send(jsonObject.toString());
//        } catch (JSONException e) {
//          e.printStackTrace();
//        } catch (Exception e) {
//          e.printStackTrace();
//        }
//      }
//      break;
//    case R.id.rewindbtn:
//      if ( LeConfig.isDeviceConnect) {
//        try {
//          JSONObject jsonObject = new JSONObject();
//          jsonObject.put("code", 202);
//          jsonObject.put("act", "ctlvideo");
//          jsonObject.put("data", "rewind");
//          SocketThreadManager.getInstance().send(jsonObject.toString());
//        } catch (JSONException e) {
//          e.printStackTrace();
//        } catch (Exception e) {
//          e.printStackTrace();
//        }
//      }
//      break;
    case R.id.connect2WifiLayout:
      Intent intent2 = new Intent(DevicePropertyActivity.this,
          ConnectWifiActivity.class);
      intent2.putExtra("fromPage", "DevicePropertyActivity");
      intent2.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
          | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent2);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;

    case R.id.breath_light_layout:
      intent = new Intent(DevicePropertyActivity.this,
          BreathLightActivity.class);
      startActivity(intent);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
    default:
      break;
    }
  }

  @Override
  public void onScroll(int l, int t, int oldl, int oldt) {
    float newAlpha = (float) t / 500;

    int height = mScrollView.getHeight();
    int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
        .getMeasuredHeight();
    int dis = scrollViewMeasuredHeight - height;
    if (dis > 0) {
      newAlpha = (float) t / dis;
    }

    if (newAlpha >= 0.8 && newAlpha <= 1.0) {
      tv_title.setText("设备");
    } else {
      tv_title.setText(strTitle);
    }

    img_headbg.setAlpha(1.0f * newAlpha);
  }

  @Override
  public void onRemoteLogin() {
    // TODO
  }

  @Override
  public void onConnectionChanged(final boolean connect) {

    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (wifiStateTv != null) {
          if (!connect) {
            LeConfig.isDeviceConnect = false;
            wifiStateTv.setText("设备未连接");
            mPowerTextView.setText("--%");
            storageTextView.setText("N/A");
            tv_title.setText("设备未连接");
            strTitle = "设备未连接";

            lastParentid = 0;
            lastVideoId = 0;

            imageCover
                .setImageResource(R.drawable.device_property_defaultcover);
            playbackryl
                .setBackgroundResource(R.drawable.device_property_defaultcoverbig);

          } else {
            LeConfig.isDeviceConnect = true;
            wifiStateTv.setText("设备已连接");

            if (Tools.isNotEmpty(mCoverUrl)) {
              showBackgroundImg(mCoverUrl);
            }

            if (Tools.isNotEmpty(strTitle) && strTitle.contains("设备未连接")) {
              strTitle = "设备已连接";
              tv_title.setText("设备已连接");
            }
          }
        }
      }
    });

  }

  @Override
  public void onPowerChanged(int power) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onUpgrade(int updatingStatus) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onCheckDeviceVersion(String version) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayNextFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayPrevFailed() {
    // TODO Auto-generated method stub

  }

  private String mCoverUrl = "";

  private void showBackgroundImg(String coverUrl) {
    ImageLoader.getInstance().displayImage(coverUrl, imageCover,
        LeXiaoXiaoBanApp.getInstance().getDisplayImageOptions());

    if (Tools.isNotEmpty(coverUrl)) {
      Picasso.with(DevicePropertyActivity.this).load(coverUrl)
          .transform(new BlurTransformation(20)).into(new Target() {
            @SuppressWarnings("deprecation")
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
              playbackryl.setBackgroundDrawable(new BitmapDrawable(bitmap));
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
              // TODO
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
              // TODO
            }
          });
    }

    mCoverUrl = coverUrl;
  }

  private void getDubDetail() {
    new AsyncTask<Void, Void, ResponseResult>() {
      @Override
      protected void onPostExecute(ResponseResult result) {
        if (Tools.isNotEmpty(result) && result.isSuccess()) {

          final CarlaClassicVo ccv = JsonSerializer.getInstance().deserialize(
              result.data, CarlaClassicVo.class);
          if (ccv != null) {
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                if (mSort > 0) {
                  strTitle = ccv.name + "第" + mSort + "集";
                } else {
                  strTitle = ccv.name;
                }

                tv_title.setText(strTitle);

              //  imgPlayMode.setEnabled(true);
//                rewindbtn.setEnabled(true);
                prebtn.setEnabled(true);
                nextbtn.setEnabled(true);
//                forward.setEnabled(true);


                showBackgroundImg(ccv.cover);
              }
            });
          }
        }
      }

      @Override
      protected ResponseResult doInBackground(Void... params) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/catalog/story/" + Parentid, param_,
            HttpUtils.TAG_GET_REQUEST);
      }

    }.execute();
  }

  private void getAlbumDetail() {
    Async.start(new Func0<ResponseResult>() {
      @Override
      public ResponseResult call() {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/catalog/album/" + Parentid, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).filter(new Func1<ResponseResult, Boolean>() {
      @Override
      public Boolean call(ResponseResult arg0) {
        return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
      }
    }).doOnCompleted(new Action0() {
      @Override
      public void call() {
        // TODO
      }
    }).subscribe(new Action1<ResponseResult>() {
      @Override
      public void call(final ResponseResult arg0) {
        if (Tools.isNotEmpty(arg0)) {
          final CartoonVo vo = JsonSerializer.getInstance().deserialize(
              arg0.data, CartoonVo.class);
          if (vo != null) {
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                if (mSort > 0) {
                  strTitle = vo.name + "第" + mSort + "集";
                } else {
                  strTitle = vo.name; // + "第" + mSort + "集";
                }

                tv_title.setText(strTitle);
                showBackgroundImg(vo.cover);
              }
            });
          }
        }
      }
    });
  }

  private int mSort;

  @Override
  public void onPlayMedia(final PlayState playState, MediaType type,
                          final JSONObject data) {
    mPlayState = playState;
    //mMediaType = type;

    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (playState.equals(PlayState.Offline)) {
       //   mMediaType = MediaType.None;
          tv_title.setText("设备未连接");
          strTitle = "设备未连接";

          lastParentid = 0;
          lastVideoId = 0;

          imageCover.setImageResource(R.drawable.device_property_defaultcover);
          playbackryl
              .setBackgroundResource(R.drawable.device_property_defaultcoverbig);

          //imgPlayMode.setEnabled(true);
//          rewindbtn.setEnabled(true);
          prebtn.setEnabled(true);
          nextbtn.setEnabled(true);
//          forward.setEnabled(true);
        } else if (playState.equals(PlayState.NoResource)
            || playState.equals(PlayState.Stop)) {
        //  mMediaType = MediaType.None;

          if (LeConfig.isDeviceConnect) {
            tv_title.setText("当前暂无播放");
            strTitle = "当前暂无播放";
          } else {
            tv_title.setText("设备未连接");
            strTitle = "设备未连接";

            lastParentid = 0;
            lastVideoId = 0;

            imageCover
                .setImageResource(R.drawable.device_property_defaultcover);
            playbackryl
                .setBackgroundResource(R.drawable.device_property_defaultcoverbig);
          }

          mPlayView.pause();

          imgPlayMode.setEnabled(true);
//          rewindbtn.setEnabled(true);
          prebtn.setEnabled(true);
          nextbtn.setEnabled(true);
//          forward.setEnabled(true);
        } else if (PlayState.Pause.equals(playState)
            || PlayState.Playing.equals(playState)) {
          if (PlayState.Playing.equals(playState)) {
            if (!mPlayView.isPlay()) {
              mPlayView.play();
            }

            play.setImageResource(R.drawable.pause_new_icon);
          }

          if (PlayState.Pause.equals(playState)) {
            mPlayView.pause();
            play.setImageResource(R.drawable.play_new_icon);
          }

          if (Tools.isNotEmpty(data)) {
            // if (data.has("VideoName")) {
            // // strTitle = data.optString("VideoName").replaceAll(".letv", "")
            // // .replaceAll(".mp3", "").replaceAll(".mp4", "");
            // // tv_title.setText(strTitle);
            // }

            if (data.has("orderid")) {
              mSort = data.optInt("orderid");
            }

            if (data.has("VideoId")) {
              VideoId = data.optInt("VideoId");

              if (VideoId == -1 && data.has("VideoName")
                  && Tools.isNotEmpty(data.optString("VideoName"))) {
                strTitle = data.optString("VideoName").replaceAll(".letv", "")
                    .replaceAll(".mp3", "").replaceAll(".mp4", "");
                tv_title.setText(strTitle);
              }
            }

            if (data.has("parentid")) {
              Parentid = data.optInt("parentid");
            }

//            if (Parentid == -1) {
//              imgPlayMode.setVisibility(View.GONE);
//            } else {
//              imgPlayMode.setVisibility(View.VISIBLE);
//            }

            if (data.has("type") && Tools.isNotEmpty(data.optString("type"))
                && data.optString("type").contains("game")) {
              tv_title.setText("互动游戏");
              strTitle = "互动游戏";

              //imgPlayMode.setEnabled(false);
//              rewindbtn.setEnabled(false);
              prebtn.setEnabled(false);
              nextbtn.setEnabled(false);
//              forward.setEnabled(false);
            } else {
              //imgPlayMode.setEnabled(true);
//              rewindbtn.setEnabled(true);
              prebtn.setEnabled(true);
              nextbtn.setEnabled(true);
//              forward.setEnabled(true);
            }

            if (data.has("type") && lastParentid != Parentid
                || data.has("type") && lastParentid == Parentid
                && lastVideoId != VideoId) {
              lastParentid = Parentid;
              lastVideoId = VideoId;

              if (Tools.isEmpty(strTitle) || Tools.isNotEmpty(strTitle)
                  && !strTitle.contains("互动游戏")) {
                if (data.has("pic") && Tools.isNotEmpty(data.optString("pic"))) {
                  runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                      showBackgroundImg(data.optString("pic"));
                    }
                  });
                } else {
                  if (data.optString("type").contains("story")
                      || data.optString("type").contains("dub")) {
                    getDubDetail();
                  } else {
                    getAlbumDetail();
                  }
                }
              }
            }
          }
        }
      }
    });

  }

  @Override
  public void onReceivedVoiceMessage(String streamUrl) {
    // TODO Auto-generated method stub

  }

  private Handler mHandler = new Handler();
  private Handler mHandler2 = new Handler();

  @Override
  public void onDataReceived(String data) {
    if (Tools.isNotEmpty(data)) {
      try {
        JSONObject jsonData = new JSONObject(data.toString());
        if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("act")) {

          String actString = jsonData.getString("act");
         String dataConntent =  jsonData.getString("data");
          if (Tools.isNotEmpty(actString)) {
            if (actString.contains("Device_Login")) {
              LeConfig.isDeviceConnect = true;


              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  wifiStateTv.setText("设备已连接");

                  if (Tools.isNotEmpty(strTitle) && strTitle.contains("设备未连接")) {
                    strTitle = "设备已连接";
                    tv_title.setText("设备已连接");
                  }

                  if (Tools.isNotEmpty(mCoverUrl)) {
                    showBackgroundImg(mCoverUrl);
                  }
                }
              });

                try {
                  JSONObject dataJson = new JSONObject();
                  dataJson.put("code", 202);
                  dataJson.put("act", "machineinfo");
                  SocketThreadManager.getInstance().send(dataJson.toString());
                } catch (JSONException e) {
                  e.printStackTrace();
                } catch (Exception e) {
                  e.printStackTrace();
                }
            } else if (actString.contains("Device_Logout")) {
              LeConfig.isDeviceConnect = false;
            } else if (actString.contains("Device_APP_Connection_Switched")) {

            } else if (actString.contains("machineinfo")) {
            //  stopCountdownTimer();
              if (Tools.isNotEmpty(dataConntent)) {
                final SocketMachineInfo sminfo = JsonSerializer.getInstance()
                    .deserialize(dataConntent,
                        SocketMachineInfo.class);

                LeConfig.isDeviceConnect = true;


                runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    wifiStateTv.setText("设备已连接");
                    if (Tools.isNotEmpty(strTitle) && strTitle.contains("设备未连接")) {
                      strTitle = "设备已连接";
                      tv_title.setText("设备已连接");

                      if (Tools.isNotEmpty(mCoverUrl)) {
                        showBackgroundImg(mCoverUrl);
                      }
                    }

                    if (Tools.isNotEmpty(sminfo)) {
                      mPowerTextView.setText(sminfo.power + "%");
                      mBatteryIndicator.updateBattery(sminfo.power / 100.0f);
                      mVersionTextView.setText("当前版本: " + sminfo.version);
                      if (sminfo.usesize != 0 && sminfo.discsize != 0) {
                        storageTextView.setText(android.text.format.Formatter
                                .formatFileSize(DevicePropertyActivity.this,
                                        (sminfo.discsize - sminfo.usesize) * 1024)
                                + "/"
                                + android.text.format.Formatter.formatFileSize(DevicePropertyActivity.this,
                                sminfo.discsize * 1024));
                      }
                      if (sminfo.discsize != 0) {
                        mStorageIndicator.convert2Angle(sminfo.discsize
                                - sminfo.usesize, sminfo.discsize);
                      }
                      if (sminfo.lightopen == 1) {
                        mProjectorCheckBox.setChecked(true);
                      } else {
                        mProjectorCheckBox.setChecked(false);
                      }

                      if (sminfo.charge == 1) {
                        mBatteryIndicator.setChargeState(true);
                      } else {
                        mBatteryIndicator.setChargeState(false);
                      }
                    }
                  }
                });
              }
            } else if (actString.contains("heart")) {
              LeConfig.isDeviceConnect = true;

              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  wifiStateTv.setText("设备已连接");
                }
              });

            }
          }
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

  }



//  @Override
//  public void onNetWorkDisconn() {
//    // TODO Auto-generated method stub
//  }
}
